<?php
/**
 * 平台工程师类
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/7/13
 * Time: 17:52
 */
namespace app\wchat\controller;

use app\repository\Repository;
use think\App;
use think\Request;

class Engin extends Common
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $row = db('admin')->where('admin_id',session('muid'))->find();

        //允许访问组
        if(!in_array($row['group_id'],[5,7,9,10])){
            $this->redirect('Pub/pub',['code'=>1]);
        }

        switch ($row['group_id']){
            case 7://调度
                $this->redirect('Control/index');
                break;
            case 9://区经理
                $this->redirect('manager/index');
                break;
            case 5://组长，组员
                if($row['is_part'] == 1){
                    //第三方工程师
                    if($row['is_group']==1){
                        $this->redirect('Teame/index');
                    }else{
                        $this->redirect('Teames/index');
                    }
                }else{
                    //平台工程师
                    if($row['is_group']==1){//组长
                        $this->redirect('Teamp/index');
                    }else{//组员
                        $this->redirect('Teamps/index');
                    }
                }
                break;
            case 10:
                $this->redirect('Power/index');
                break;
        }


        //如果是第三方工程师
        /*if($row['is_part'] == 1){
            $this->redirect('Otherengin/index');
        }*/

        $au = [
            'dis'=>320
        ];

        $action = $this->request->action();

        $action = strtolower($action);

        if(!empty($au[$action])){
            if(!($this->isAuth($au[$action],$row['group_id']))){
                $this->error('您无此操作权限');
            }
        }

    }

    private function isAuth($id,$gid){

        if(!session('auth')){
            $val = db('auth_group')->where('group_id',$gid)->value('rules');
            session('auth',explode(',',$val));
        }

        return in_array($id,session('auth'));
    }

    /**
     * 平台工程师主页
     * @return mixed
     */
    public function index(){
        return $this->fetch('index');
    }

    /**
     * 任务列表页面
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');    
    }

    /**
     * 工单列表页面
     * @return mixed
     */
    public function workListUI()
    {
        return $this->fetch('workList');
    }

    /**
     * 是的接单
     */
    public function disListUI(){
        return $this->fetch('disList');
    }
    /**
     * 创建工单
     * @return mixed
     */
    public function addWorkUI(){
        return $this->fetch('addWork');
    }

    /**
     * 创建任务页面
     * @return mixed
     */
    public function addDisUI(){
        return $this->fetch('addDis');
    }

    /**
     * 派单于第三方
     * @return mixed
     */
    public function sendThirdUI(){
        return $this->fetch('sendThird');
    }

    /**
     * 出借列表
     * @return mixed
     */
    public function leadUI(){
        return $this->fetch('lead');
    }

    public function lendRecUI(){
        return $this->fetch('lendrec');
    }

    /**
     * 跟踪列表
     * @param Request $request
     */
    public function track(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];

        $rows = db('dispatch_flow')->alias('df')
            ->order('df.id desc')
            ->where('df.dispatch_id',$did)
            ->join('admin a','a.admin_id=df.admin_id','left')
            ->field(['df.*','a.username'])
            ->select();
        return ['code'=>1,'data'=>$rows];
    }

    /**
     * 详情页面
     * @return mixed
     */
    public function getDisUI(){

        $id = input('id');

        if(empty($id)){
            $row = db('dispatch')->where('works_id',input('wid'))->field(['id'])->find();
            $id = $row['id'];
        }
        $info = db('dispatch')->alias('w')->where('w.id',$id)
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->find();
        return $this->fetch('getDis',['info'=>$info]);
    }

    public function getWorkUI(){

        $id = input('id');

        $info = db('works')->alias('w')->where('w.id',$id)
            ->join('state st','st.id=w.state_id','left')
            ->join('works_type wt','wt.id=w.type_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->field(['w.*','st.state_name','wt.type_name','ft.title as fault_name'])
            ->find();

        return $this->fetch('getWork',['info'=>$info]);
    }

    /**
     * 跟踪
     * @return mixed
     */
    public function trackUI(){
        return $this->fetch('track');
    }

    /**
     * 工程师派单
     * @return mixed
     */
    public function sendEnginUI(){
        return $this->fetch('sendEngin');
    }

    /**
     * 工单列表
     * @param Request $request
     * @return array
     */
    public function queryWork(Request $request)
    {
        $input = $request->param();

        $input['gid'] = session('mgid');

        $rows = db('works')->alias('w')->where(function ($query)use($input){

            if(!empty($input['id'])){
                $query->where('w.id',$input['id']);
            }

            if(!empty($input['number'])){
                $query->where('w.number',$input['number']);
            }
            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }
            if(!empty($input['tel'])){
                $query->where('w.tel',$input['tel']);
            }
            if(!empty($input['type_id'])){
                $query->where('w.type_id',$input['type_id']);
            }
            if(isset($input['is_inner'])){
                $query->where('w.is_inner',$input['is_inner']);
            }
            if($input['gid']==5){
                $query->where('w.admin_id',session('muid'));
            }
            if(!empty($input['key'])){
                $query->where('w.title','LIKE','%'.$input['key'].'%');
                $query->whereOr('w.number',$input['key']);
            }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('works_type wt','wt.id=w.type_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->field(['w.*','st.state_name','wt.type_name','ft.title as fault_name'])
            ->paginate($input['limit'])
            ->toArray();

        return ['code'=>1,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }


    /**
     * 派单任务列表
     * @param Request $request
     * @return array
     */
    public function queryDis(Request $request){
        $input = $request->param();
        $input['gid'] = session('mgid');
        $rows = db('dispatch')->alias('w')->order('w.id desc')->where(function ($query)use($input){

            if($input['gid'] == 7){

            }else{
                $query->where('w.engin_id',session('muid'));
            }


            if(!empty($input['id'])){
                $query->where('w.id',$input['id']);
            }

            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }
            if(!empty($input['tel'])){
                $query->where('w.tel',$input['tel']);
            }

            if(!empty($input['key'])){
                $query->where('w.title|ws.number|w.tel','LIKE','%'.$input['key'].'%');
            }

            if(!empty($input['admin_id'])){
                $query->where('w.admin_id',$input['admin_id']);
            }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->paginate($input['limit'])
            ->toArray();
        return ['code'=>1,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }

    /**
     * 创建派单任务
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addDis(Request $request){
        $input = $request->param();

        $input['state_id'] = 20;

        $msg = $this->validate($input,'app\admin\validate\Dispatch');
        if(!$msg){
            return ['code'=>0,'msg'=>$msg];
        }

        if(!empty($input['works_id'])){

            $info = db('works')->where('id',$input['works_id'])->find();

            if($info['state_id'] >= 12){
                return ['code'=>0,'msg'=>'该工单不可创建任务单'];
            }

            db('works')->where('id',$input['works_id'])->update(['state_id'=>12]);
        }

        if(!empty($input['admin_id'])){
            $input['state_id'] = 22;
        }

        $input['number'] = 'D'.date("YmdH",time()).rand(101,999);
        $input['engin_id'] = session('muid');

        $did = db('dispatch')->insertGetId($input);


        if($did)
            return ['code'=>1,'msg'=>'创建成功'];
        return ['code'=>0,'msg'=>'创建失败'];
    }

    /**
     * 派单给第三方
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function dis(Request $request){

        $id = $request->param('id');
        $aid = $request->param('aid');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'请选择第三方'];

        $info = db('dispatch')->where('id',$id)->find();

        if(!empty($info['admin_id']) && $info['state_id'] != 23)
            return ['code'=>0,'msg'=>'该任务单已派该给第三方'];

        $row = db('dispatch')->where('id',$id)->update(['admin_id'=>$aid,'state_id'=>22]);
        if($row)
            return ['code'=>1,'msg'=>'派单成功'];
        return ['code'=>0,'msg'=>'派单失败'];
    }
    //派单给工程师
    public function disToEngin(Request $request){
        $id = $request->param('id');
        $aid = $request->param('aid');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'请选择工程师'];
        $row = db('dispatch')->where('id',$id)->update(['admin_id'=>$aid,'state_id'=>22]);
        if($row){

            \app\repository\Dispatch::addTeam($id,$aid,'wchat/Enginme/getUI');
            \app\repository\Dispatch::lead($id,$aid);

            return ['code'=>1,'msg'=>'派单成功'];
        }

        return ['code'=>0,'msg'=>'派单失败'];
    }

    /**
     * 关闭工单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function closeWork(Request $request){
        $id = $request->param('id');
        $info = db('works')->where('id',$id)->find();
        if($info['state_id']==12 || $info['state_id'] == 13){
            return ['code'=>0,'msg'=>'工单不可关闭'];
        }
        $row = db('works')->where('id',$id)->update(['state_id'=>14]);

        if($row)
            return ['code'=>1,'msg'=>'关闭成功'];
        return ['code'=>0,'msg'=>'关闭失败'];

    }


    /**
     * 故障列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function faults(){
        $rows = db('fault')->order('sort asc')->select();

        $data = [];
        foreach ($rows as $v){
            $data[] = [
                'value'=>$v['title'],
                'id'=>$v['id']
            ];
        }

        return ['code'=>1,'data'=>$data];

    }

    /**
     * 三方单位列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function party(){
        $row = db('admin')->where('group_id',6)->select();
        $data = [];
        foreach ($row as $v){
            $data[] = ['value'=>$v['username'].'('.$v['name'].')','id'=>$v['admin_id']];
        }
        return ['code'=>1,'data'=>$data];
    }

    /**
     * 平台工程师列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function engins(){
        $row = db('admin')->where('group_id',5)->select();
        $data = [];
        foreach ($row as $v){
            $data[] = ['value'=>$v['username'].'('.$v['name'].')','id'=>$v['admin_id']];
        }
        return ['code'=>1,'data'=>$data];
    }
    /**
     * 出借记录
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queryLend(Request $request){
        $input = $request->param();

        $input['input_id'] = session('muid');

        $rows = db('tools_lend')->alias('tl')
            ->order('tl.id desc')
            ->where(function ($query)use($input){
                if(!empty($input['input_id']))
                    $query->where('tl.input_id',$input['input_id']);
                if(!empty($input['state_id']))
                    $query->where('tl.state_id',$input['state_id']);
            })
            ->join('admin a','a.admin_id=tl.admin_id','left')
            ->join('state st','st.id=tl.state_id','left')
            ->field(['tl.*','a.username','a.name','st.state_name'])
            ->paginate($input['limit'])->toArray();

        return ['code'=>1,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total']];
    }

    /**
     * 出借列表
     * @param Request $request
     * @return array
     */
    public function lendRecord(Request $request){
        $did = $request->param('did');
        if(empty($did)) return ['code'=>0,'msg'=>'id参数错误'];
        $row = db('tools_lend_record')->alias('tr')->where('tr.lend_id',$did)
            ->join('state st','st.id=tr.state_id','left')
            ->select();
        return ['code'=>1,'data'=>$row];
    }

}